import os
import pathlib
import tkinter as tk
from tkinter import messagebox

from entity.Image import Image


class File:
    def __init__(self, ddt, path):
        if path == "return":
            self.name = ""
        else:
            self.name = path.name
        self.root = ddt
        self.path = path
        self.canvas = None
        self.width = 90
        self.height = 90

    def set_image_to_window(self, row, column, image):
        self.canvas = tk.Canvas(self.root.catalogue)
        img = tk.Label(self.canvas, image=image, width=self.width, height=self.height, cursor="plus")
        text = tk.Label(self.canvas, text=self.name)
        img.bind("<Double-Button-1>", self.click)
        img.grid(row=0, column=0)
        text.grid(row=1, column=0)
        self.canvas.grid(row=row, column=column, sticky=tk.NW, ipadx=5, ipady=5)

    def click(self, event):
        if self.name == "":
            self.root.return_parent()
            return 0
        if self.path.suffix == ".jpg":
            """编辑特征"""
            self.root.Image = Image()
            if not self.root.Image.set(self.path):
                self.root.err_log(f"图片已损坏: {self.path}")
                if messagebox.askokcancel("提示", "是否删除？"):
                    os.remove(str(self.path))
                    self.root.err_log(f"{self.path}已删除")
                    self.root.load_catalogue(self.path.parent)
                self.root.Image = None
                return 0
            self.root.open_type = False
            self.root.get_image_to_ddt()
            return 0
        if self.path.name == "app.dsft.ini":
            """打开配置文件"""
            self.root.open_type = True
            self.root.get_config_to_ddt()
            return 0
        if self.path.is_dir():
            self.root.load_catalogue(self.path)
